<template>
  <div>
    <div id="world-map" style="width: 100%; height: 100%"></div>
  </div>
</template>


<!-- <script
     type="text/javascript"
     src="http://api.tianditu.gov.cn/api?v=4.0&tk=33752fcceac2cec91dcd788b342fba06"
   ></script> -->
   <script
   type="text/javascript"
   src="https://gis.soszyzg.com/tdtapi?v=4.0&tk=33752fcceac2cec91dcd788b342fba06"
 ></script>

<script>
export default {
  data() {
    return {
      tmap: null,
    };
  },
  props: {
    // baseTable: {},
    sContent: {},
  },
  mounted() {
    this.loadTiandituScript()
      .then(() => {
        console.log("初始化地图");
        this.initTMap(); // 脚本加载后初始化地图
      })
      .catch((error) => {
        console.error("Failed to load Tianditu API script:", error);
      });
  },
  methods: {
    // 动态加载天地图脚本
    loadTiandituScript() {
      return new Promise((resolve, reject) => {
        if (typeof T !== "undefined") {
          resolve(); // 如果 T 已经存在，直接 resolve
        } else {
          const script = document.createElement("script");
          script.src =
            // "http://api.tianditu.gov.cn/api?v=4.0&tk=33752fcceac2cec91dcd788b342fba06";
            "https://gis.soszyzg.com/tdtapi?v=4.0&tk=33752fcceac2cec91dcd788b342fba06";
          script.onload = resolve;
          script.onerror = reject;
          document.head.appendChild(script);
        }
      });
    },
    // 初始化天地图
    initTMap() {
      console.log("initTMap==");
      this.tmap = new T.Map("world-map");
      this.tmap.centerAndZoom(new T.LngLat(104.087715, 30.567811), 12);
      this.tmap.enableScrollWheelZoom(true);
    },
    // 聚合点数据
    pointDataMap(val) {
      console.log(1231, val);
      var that = this;
      if (val.length > 0) {
        // if (this.markers && this.markers.length > 0) {
        //   this.clearLayer();
        // }
        this.markers = [];
        val.forEach((e, i) => {
          let pt = new T.LngLat(e.lng, e.lat);
          // 设置自定义图标
          let icon = new T.Icon({
            iconUrl: e.defaultIcon
              ? e.defaultIcon
              : "https://gis.soszyzg.com/tdtimages/bus/start.png", // 设置图标 URL
            iconSize: new T.Point(50, 50), // 图标大小
            iconAnchor: new T.Point(25, 50), // 图标锚点
          });
          let marker = new T.Marker(pt, { icon: icon });
          if (!marker) {
            console.error("Marker creation failed.");
          }
          let label = new T.Label({
            text: e.hbCarNo,
            position: pt,
            offset: new T.Point(-50, -65),
          });
          if (!label) {
            console.error("Label creation failed.");
          }
          try {
            if (this.tmap && marker) {
              this.tmap.addOverLay(marker);
            }
            if (this.tmap && label) {
              this.tmap.addOverLay(label);
            }
          } catch (error) {
            console.error("Error in adding overlay:", error);
          }
          //设置显示地图的中心点和级别
          // if (i == 0) {
          //   this.tmap.centerAndZoom(new T.LngLat(val[0].lng, val[0].lat), 13);
          // }

          marker.addEventListener("click", function () {
            // 自定义弹窗逻辑
            // that.carFrame(e);
            console.log(that.sContent, "sContent");

            // 创建自定义信息窗口
            let infoBox = new T.InfoWindow(that.sContent, {
              offset: new T.Point(0, -30),
              closeOnClick: true, //允许点击地图关闭窗口
              closeButton: false, //是否显示关闭按钮
            });

            // // 如果有之前的自定义窗口，关闭它
            // if (that.lastInfoBox) {
            //   that.lastInfoBox.close();
            // }

            // 关闭天地图可能自动弹出的默认 InfoWindow
            that.tmap.closeInfoWindow(); // 检查是否有这样的方法

            // 保存并显示自定义的 InfoWindow
            that.lastInfoBox = infoBox;
            that.tmap.openInfoWindow(infoBox, pt);
          });

          this.markers.push(marker);
        });

        if (this.markerClusterer) {
          this.markerClusterer.clearMarkers();
        }
        this.markerClusterer = new T.MarkerClusterer(this.tmap, {
          markers: this.markers,
        });
        this.tmap.addEventListener("load", () => {
          // 确保地图加载完毕后添加标记
          this.markerClusterer.addMarkers(this.markers);
        });
      }
    },
    // 绘制矢量图层
    drawLayer(val) {
      this.clearLayer();
      let ponintarr = [];
      val.forEach((e) => {
        console.log(e, "===e围栏数据");
        if (e.fenceType === "circle") {
          let val = JSON.parse(e.detail);
          // this.addCircle(e.lng, e.lat, e.radius);
          let lng = val.center[0];
          let lat = val.center[1];
          let radius = val.r;
          console.log("=======>", lng, lat, radius);
          this.tmap.centerAndZoom(new T.LngLat(lng, lat), 13);
          this.addCircle(lng, lat, radius);
        } else if (e.fenceType === "polygon") {
          let val = JSON.parse(e.detail);
          if (val.length > 0) {
            this.tmap.centerAndZoom(new T.LngLat(val[0][0], val[1][1]), 13);
          }
          this.addPolygon(val);
        }
        ponintarr.push(...e.carInfo);
      });
      setTimeout(() => {
        console.log("聚合数组", ponintarr);
        this.pointDataMap(ponintarr);
      }, 700);
    },
    // 添加圆
    addCircle(lng, lat, radius) {
      const circle = new T.Circle(new T.LngLat(lng, lat), radius, {
        color: "red",
        weight: 2,
        opacity: 0.2,
        fillColor: "pink",
        fillOpacity: 0.4,
      });
      this.circle = circle;

      this.tmap.addOverLay(circle);
    },

    // 添加多边形
    addPolygon(points = []) {
      let pointArr = points.map((item) => new T.LngLat(item[0], item[1]));
      const polygon = new T.Polygon(pointArr, {
        color: "red",
        weight: 2,
        opacity: 0.2,
        fillColor: "pink",
        fillOpacity: 0.4,
      });
      this.polygon = polygon;

      this.tmap.addOverLay(polygon);
    },

    //新增矢量图层
    Addgraph(val) {
      this.clearLayer();
      if (val === "circle") {
        this.drawCircle();
      } else if (val === "polygon") {
        this.drawPolygon();
      }
    },
    // 绘制圆
    drawCircle() {
      let that = this;
      const circleTool = new T.CircleTool(this.tmap, {
        color: "red",
        weight: 2,
        opacity: 0.2,
        fillColor: "pink",
        fillOpacity: 0.4,
      });
      circleTool.open();
      circleTool.on("drawend", function (e) {
        // onDrawCircle(e.currentCenter, e.currentRadius);
        let center = e.currentCenter;
        let radius = e.currentRadius;
        console.log("===返回圆的中心点", center, center.lng, center.lat);
        console.log("===返回圆的半径", radius);

        let obj = {
          r: radius,
          center: [center.lng, center.lat],
        };
        let val = {
          detail: obj,
          fenceType: "circle",
        };
        that.$emit("saveFenceInfo", val);
      });
    },
    // 绘制多边形
    drawPolygon() {
      let that = this;
      const polygonTool = new T.PolygonTool(this.tmap, {
        color: "red",
        weight: 2,
        opacity: 0.2,
        fillColor: "pink",
        fillOpacity: 0.4,
      });
      polygonTool.open();
      polygonTool.on("draw", function (e) {
        console.log("===返回多边形的点数组", e.currentLnglats);

        let obj = e.currentLnglats.map((item) => [item.lng, item.lat]);
        let val = {
          detail: obj,
          fenceType: "polygon",
        };
        console.log(val);
        that.$emit("saveFenceInfo", val);
      });
    },

    // 清除图层覆盖物
    clearLayer() {
      this.tmap.clearOverLays();
    },

    // 启动圆的编辑
    editCircle(circle) {
      circle = this.circle;
      circle.enableEdit();
    },
    // 启动多边形的编辑
    editPolygon(polygon) {
      console.log("=====多", this.polygon);
      polygon = this.polygon;
      polygon.enableEdit();
    },

    // 结束圆编辑并保存
    endeditCircle() {
      this.circle.disableEdit();
      console.log("===返回圆的中心点", this.circle.getCenter());
      console.log("===返回圆的半径", this.circle.getRadius());
      let lng = this.circle.getCenter().lng;
      let lat = this.circle.getCenter().lat;
      let radius = this.circle.getRadius();
      let obj = {
        r: radius,
        center: [lng, lat],
      };
      let val = {
        detail: obj,
        fenceType: "circle",
      };
      this.$emit("saveFenceInfo", val);
    },
    // 结束多边形编辑并保存
    endeditPolygon() {
      this.polygon.disableEdit();
      console.log("===返回多边形的点数组", this.polygon.getLngLats());
      let obj = this.polygon
        .getLngLats()[0]
        .map((item) => [item.lng, item.lat]);

      let val = {
        detail: obj,
        fenceType: "polygon",
      };
      console.log(val);
      this.$emit("saveFenceInfo", val);
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .tdt-infowindow-content {
  margin: 0 !important;
}
</style>
